import nodemailer from 'nodemailer';
import expressAsyncHandler from 'express-async-handler';

const port = process.env.PORT || 3000; // 获取端口号

/**
 * 使用Express的异步处理器发送密码重置邮件
 * @param {Object} user - 用户对象，包含用户的电子邮件和姓名
 * @param {String} resetToken - 用于重置密码的令牌
 */
const sendPasswordResetEmail = expressAsyncHandler(async (user, resetToken) => {
  try {
    // 创建一个SMTP客户端，用于发送邮件
    const transporter = nodemailer.createTransport({
      service: 'qq',
      host: 'smtp.qq.com',
      port: 465, // SMTP服务器的端口
      secure: true, // 使用SSL加密连接
      auth: {
        user: process.env.EMAIL,
        pass: process.env.EMAIL_PASSWORD,
      },
      debug: true,
      logger: true,
    });

    // 构建重置密码的URL
    const resetUrl = `http://localhost:${port}/reset-password/${resetToken}`;

    // 构建邮件的HTML内容
    const emailContent = `
        <div style="font-family: Arial, sans-serif; background-color: #f8f8f8; padding: 20px;">
          <div style="background-color: #ffffff; padding: 20px; border-radius: 5px;">
            <p style="text-align: center;">Hi ${user.name}</p>
            <h1 style="text-align: center; color: #333;">Reset Your Password</h1>
            <p style="text-align: center; color: #333;">
              Please click on the button below to reset your password.
            </p>
            <div style="text-align: center;">
            <a href="${resetUrl}" style="display: inline-block; padding: 10px 20px; background-color: #007bff; color: #ffffff; text-decoration: none; border-radius: 5px;">
                Reset Password
              </a>
            </div>
          </div>
        </div>
      `;

    // 配置邮件选项
    const mailOptions = {
      from: process.env.EMAIL,
      to: user.email,
      subject: 'Password Reset Request',
      text: `You requested a password reset. Click the link to reset your password: ${resetUrl}`,
      // html: `<p>You requested a password reset. Click the link to reset your password:</p><a href="${resetUrl}">${resetUrl}</a>`,
      html: emailContent,
    };

    // 验证SMTP客户端是否配置正确
    transporter.verify(function (error, success) {
      if (error) {
        console.error('Verification error:', error);
      } else {
        console.log('Server is ready to take our messages');
      }
    });

    // 发送邮件
    await transporter.sendMail(mailOptions);
    console.log('Password reset email sent successfully');
  } catch (error) {
    console.error('Error sending password reset email:', error);
  }
});


export { sendPasswordResetEmail };
